package com.demo.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ZKConnectSessionWatcher implements Watcher {
    final static Logger log = LoggerFactory.getLogger(ZKConnectSessionWatcher.class);
    public static final String zkServerPath = "127.0.0.1:12181";
    public static final Integer timeout = 5000;

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher());
        long sessionId = zk.getSessionId();
        String ssid = "0x" + Long.toHexString(sessionId);
        System.out.println(ssid);
        byte[] sessionPassword = zk.getSessionPasswd();

        log.warn("客户端开始连接zookeeper服务器...");
        log.warn("连接状态：{}", zk.getState());
        Thread.sleep(1000);
        log.warn("连接状态：{}", zk.getState());

        Thread.sleep(200);
        log.warn("开始会话重连...");

        ZooKeeper zkSession = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher(), sessionId, sessionPassword);
        log.warn("连接状态：{}", zkSession.getState());
        Thread.sleep(1000);
        log.warn("连接状态：{}", zkSession.getState());
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        log.warn("接收到watch通知: {}", watchedEvent);
    }
}
